package com.project.common.screens;

import teacher.MySchedules;
import teacher.NewSchedule;
import teacher.UploadForm;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import applicationDAO.Institute;
import classroom.OverAllRating;
import classroom.Selector;

import com.project.trac.R;

import core.communication.IMService;
import core.interfaces.IAppManager;
import core.ui.FriendList;
import finder.ActivityManager;

public class Dashboard extends Institute implements OnItemClickListener {
	
	private GridView menu;
	
	private String[] MENU_STUDENT = 
		{ "Class Schedules", "My Classes", "My Class Ratings", "Messenger" };
	
	private String[] MENU_TEACHER = 
		{ "New Schedule", "My Classes", "Upload File", "Attendance", "Export Gradesheet"};
	
	private Integer[] ICONSET_STUDENT = {
			R.drawable.course,
			R.drawable.classroom,
			R.drawable.rating,
			R.drawable.ic_launcher
	};
	
	private Integer[] ICONSET_TEACHER = {
			R.drawable.classroom,
			R.drawable.apple,
			R.drawable.ic_launcher,
			R.drawable.ic_launcher,
			R.drawable.ic_launcher,
			R.drawable.ic_launcher
	};
	
	
	
	protected static final int NOT_CONNECTED_TO_SERVICE = 0;
	protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
	protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2 ;
	protected static final int NOT_CONNECTED_TO_NETWORK = 3;
	public static final String AUTHENTICATION_FAILED = "0";
	public static final String FRIEND_LIST = "FRIEND_LIST";
	private IAppManager imService;

	
	  private ServiceConnection mConnection = new ServiceConnection() {
	        public void onServiceConnected(ComponentName className, IBinder service) {
	            // This is called when the connection with the service has been
	            // established, giving us the service object we can use to
	            // interact with the service.  Because we have bound to a explicit
	            // service that we know is running in our own process, we can
	            // cast its IBinder to a concrete class and directly access it.
	            imService = ((IMService.IMBinder)service).getService();  
	            
	            if (imService.isUserAuthenticated() == true)
	            {
					startActivity(new Intent(Dashboard.this, FriendList.class));
	            }
	        }

	        public void onServiceDisconnected(ComponentName className) {
	            // This is called when the connection with the service has been
	            // unexpectedly disconnected -- that is, its process crashed.
	            // Because it is running in our same process, we should never
	            // see this happen.
	        	imService = null;
	            Toast.makeText(getApplicationContext(), R.string.local_service_stop,
	                    Toast.LENGTH_SHORT).show();
	        }
	    };
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main_panel);
		setTitle(getFirstName() + "'s Dashboard");
		System.out.println(getUsername() + " " + getPassword());

		menu = (GridView) findViewById(R.id.Menu);
		menu.setOnItemClickListener(this);
		
		if (getRole() == 0) {
			menu.setAdapter(new MenuItem(this, R.layout.layout_main_panel_item, MENU_TEACHER));
		} else {
			menu.setAdapter(new MenuItem(this, R.layout.layout_main_panel_item, MENU_STUDENT));
		}
		
		Toast.makeText(getBaseContext(), "Welcome, " + getFirstName() + "!", Toast.LENGTH_LONG).show();
		
	}

	private class MenuItem extends ArrayAdapter<Object> {
		
		public MenuItem(Context context, int textViewResourceId, String[] objects) {
			super(context, textViewResourceId, objects);
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.layout_main_panel_item, parent, false);
			TextView tv = (TextView) row.findViewById(R.id.text);
			
			switch(getRole()) {
			
			case 0:
					tv.setText(MENU_TEACHER[position]);
					tv.setCompoundDrawablesWithIntrinsicBounds(0, ICONSET_TEACHER[position], 0, 0);
				break;
			case 1:
					tv.setText(MENU_STUDENT[position]);
					tv.setCompoundDrawablesWithIntrinsicBounds(0, ICONSET_STUDENT[position], 0, 0);
				break;
			default: { break;}
			}
			
			return row;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> av, View view, int position, long id) {
		
		if (getRole() == 0) {
			switch (position) {
				case 0:
					startActivity(new Intent(getApplication(), NewSchedule.class));
					break;
				case 1:
					startActivity(new Intent(getApplication(), MySchedules.class));
					break;
				case 2:
					startActivity(new Intent(getApplication(), UploadForm.class));
					break;
				case 3:
				case 4:
					Toast.makeText(getBaseContext(), "not yet implemented!", Toast.LENGTH_LONG).show();
					break;
			default: { break; }
			}
		}
		
		if (getRole() == 1) {
			switch (position) {
				case 0:
					startActivity(new Intent(getApplication(), ActivityManager.class));
					break;
				case 1:
					startActivity(new Intent(getApplication(), Selector.class));
					break;
				case 2:
					startActivity(new Intent(getApplication(), OverAllRating.class));
					break;
				case 3:
				
					break;
				default: { break; }
			}
		}
		
	}
	
	@Override
	protected void onPause() {
		unbindService(mConnection);
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		bindService(new Intent(Dashboard.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
		super.onResume();
	}

	private long lastPress;
	@Override
	public void onBackPressed() {
		
	    long currentTime = System.currentTimeMillis();
	    
	    if (currentTime - lastPress > 3500){
	    	TextView msg = new TextView(this);
			msg.setText("You will be logged out of the system");
			msg.setTextAppearance(getApplication(), R.style.alert_message);
			msg.setGravity(Gravity.CENTER_HORIZONTAL);

			new AlertDialog.Builder(this)
			.setTitle("Information")
			.setView(msg)
			.setIcon(android.R.drawable.ic_dialog_info)
			.setCancelable(false)
			.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					Intent i = new Intent (getApplication(), Login.class);
					startActivity(i);
					finish();
				}
			})
			.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,int id) {
					dialog.cancel();
				}
			}).create().show();
	        lastPress = currentTime;
	    } else {
	        super.onBackPressed();
	    }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
}